import BaseController from '../../core/controllers/Base.controller';
import storageApi from '../../core/storage/storage';
import './workerInfo.scss';

@Inject('$log', '$rootScope', 'globalService', 'staffService', 'ngDialog', 'ngDialogService')
class WorkerInfoController extends BaseController {
  constructor() {
    super();

    this.paginationService = this.staffService;
    this.$setQueryCallback((res) => {
      this.workerListData = res.rows;
    });

    this.mapParams = {
      orgId: $rootScope.orgId || storageApi.get('orgId'),
      // fullName: '',
      // code: '',
      // idNo: '',
      // postCode: '',
      // departmentCode: '',
      // inOutStatus: '',
      // isSpecial: '',
      // startTime: '',
      // endTime: '',
      // sortType: 1,
    };
    this.mapParams.inOutStatus = '';

    this.$paginationQuery();
    // 全选
    this.toggleAllFlag = false;
  }

  $reset() {
    this.mapParams = {
      orgId: this.$rootScope.orgId || storageApi.get('orgId'),
      inOutStatus: this.mapParams.inOutStatus,
    };
    // this.mapParams = {
    //   orgId: this.$rootScope.orgId || storageApi.get('orgId'),
    //   fullName: '',
    //   code: '',
    //   idNo: '',
    //   postCode: '',
    //   departmentCode: '',
    //   inOutStatus: '',
    //   isSpecial: '',
    //   startTime: null,
    //   endTime: null,
    // };
  }

  $delete(id) {
    this.ngDialogService.confirm('确定删除此数据吗？', id)
      .then((data) => {
        this.$log.debug(data);
        this.staffService
          .delete([id])
          .then((res) => {
            if (res.success) {
              this.ngDialogService.alertSuccess(res.message);
              this.$paginationQuery();
            }
          });
      });
  }

  /*eslint-disable */
  $toggleAll() {
    this.workerListData.forEach((item) => {
      item.checked = this.toggleAllFlag;
    });
  }

  // 判断全选人
  $isChange() {
    let bool = true;
    this.workerListData.forEach((item) => {
      if (!item.checked) {
        bool = false;
      }
    });
    this.toggleAllFlag = bool;
  }

  // 获取选中人员信息
  $getSelectedWorkers() {
    let selectedWorkerList = [];
    if (this.workerListData) {
      let length = this.workerListData.length;
      for (let i = 0; i < length; i++) {
        let item = this.workerListData[i];
        if (item.checked) {
          selectedWorkerList.push(item);
        }
      }
      return selectedWorkerList;
    }
  }

  // 进场登记
  $intoRegistration(sysCtrl) {
    let ids = [], outTime = [];
    let selectedWorkerList = this.$getSelectedWorkers();
    let workerStatusCheck = true;
    let dialogPrompt = '';
    if (!selectedWorkerList.length) {
      this.ngDialogService.alertError('请选择人员');
      return;
    };
    selectedWorkerList.forEach((item) => {
      if (item.inOutStatus === '1') {
        dialogPrompt +=`${item.fullName}[${item.code}]\n`;
        workerStatusCheck = false;
      } else {
        ids.push(item.id);
        outTime.push(item.outTime);
      }
    });
    if (workerStatusCheck) {
      this.ngDialog.open({
        template: 'paIntoRegistrationDialog',
        className: 'ngdialog-theme-default pa-in-out-registration',
        controllerAs: 'vm',
        controller($scope, staffService, ngDialogService) {
          'ngInject';

          const max = _.max(outTime);
          const date = new Date(parseInt(max));
          this.month = date.getMonth() + 1;
          this.day = date.getDate();
          if (this.month < 10) {
            this.month = '0' + this.month;
          }
          if (this.day < 10) {
            this.day = '0' + this.day;
          }
          const timeStr = date.getFullYear() + '-' + this.month + '-' + this.day;
          this.sureBtnFn = () => {
            if (this.recordTime < timeStr) {
              ngDialogService.alertError('进场时间应该大于出场时间');
              return false;
            }
            const reqData = {
              staffIds : ids,
              recordTime : this.recordTime,
            };
            staffService
              .saveInTime(reqData)
              .then((res) => {
                sysCtrl.$paginationQuery();
                ngDialogService.alertSuccess(res.message);
                sysCtrl.toggleAllFlag = false;
              });
            $scope.closeThisDialog();
          };
        },
      });
    } else {
      this.ngDialogService.alertError(`${dialogPrompt}已在场，请 重新选择`);
      return;
    }
  }

  // 离场登记
  $outRegistration(sysCtrl) {
    let ids = [], inTime = [];
    let selectedWorkerList = this.$getSelectedWorkers();
    let workerStatusCheck = true;
    let dialogPrompt = '';
    if (!selectedWorkerList.length) {
      this.ngDialogService.alertError('请选择人员');
      return;
    };
    selectedWorkerList.forEach((item) => {
      this.$log.debug(item.inOutStatus, typeof item.inOutStatus);
      if (item.inOutStatus === '2') {
        dialogPrompt +=`${item.fullName}[${item.code}]\n`;
        workerStatusCheck = false;
      } else {
        ids.push(item.id);
        inTime.push(item.inTime);
      }
    });
    if (workerStatusCheck) {
      this.ngDialog.open({
        template: 'paOutRegistrationDialog',
        className: 'ngdialog-theme-default pa-in-out-registration',
        controllerAs: 'vm',
        controller($scope, $log, staffService, ngDialogService) {
          'ngInject';

          const max = _.max(inTime);
          const date = new Date(parseInt(max));
          this.month = date.getMonth() + 1;
          this.day = date.getDate();
          if (this.month < 10) {
            this.month = '0' + this.month;
          }
          if (this.day < 10) {
            this.day = '0' + this.day;
          }
          const timeStr = date.getFullYear() + '-' + this.month + '-' + this.day;
          this.sureBtnFn = () => {
            if (this.recordTime < timeStr) {
              ngDialogService.alertError('出场时间应该大于进场时间');
              return false;
            }
            const reqData = {
              staffIds : ids,
              recordTime : this.recordTime,
            };
            staffService
              .saveOutTime(reqData)
              .then((res) => {
                sysCtrl.$paginationQuery();
                ngDialogService.alertSuccess(res.message);
                sysCtrl.toggleAllFlag = false;
              });
            $scope.closeThisDialog();
          };
        },
      });
    } else {
      this.ngDialogService.alertError(`${dialogPrompt}已离场，请 重新选择`);
      return;
    }
  }

  // 打印二维码
  $printQrCode(sysCtrl) {
    let selectedWorkerList = this.$getSelectedWorkers();
    if (!selectedWorkerList.length) {
      this.ngDialogService.alertError('请选择人员');
      return;
    }
    this.selectedWorkerList = selectedWorkerList;
    this.ngDialog.open({
      template: 'workerInfoQrCodePrintDialog',
      className: 'ngdialog-theme-default pa-in-out-registration',
      controllerAs: 'vm',
      controller($scope) {
        'ngInject';

        this.selectedWorkerList = sysCtrl.selectedWorkerList;

        this.print = () => {
          $('.qr-print').print({ globalStyles: false, timeout: 1200 });
        }

        this.getQrCodeSrc = (item) => {
          let codeJson = {
            id: item.id,
            type: 1, // 1:人员、设备
          }
          codeJson = JSON.stringify(codeJson);
          let qrContent = encodeURIComponent(codeJson);
          let requestUrlStr = `/sgms/api/v1/common/qr?size=160&code=${qrContent}`;
          return requestUrlStr;
        }
      },
    });
  }
}

console.dir(WorkerInfoController);
export default WorkerInfoController;
// export default angular
//   .module('worker.list', [])
//   .controller(WorkerInfoController.name, WorkerInfoController);
